package com.mp.approvalreq.util;

import com.mp.approvalreq.entity.ConditionFlow;
import com.mp.user.entity.User;
import com.plusmoney.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by liuqi on 2018/6/4.
 */
public class ApprovalAuthUtils {
    private static final Logger logger = LoggerFactory.getLogger(ApprovalAuthUtils.class);

    /**
     * 提交审批时,灵活审批流追加审批权限
     *
     * @param flows
     * @param user
     */
    public static void addAuthForJudger(String flows, User user) {
        try {
            Set<String> ids = getIds(flows);
            if (Utils.isEmpty(ids)) {
                return;
            }
            RocketUtils.sendAddAuthMsg(Utils.collection2string(ids), user.getCompanyId());
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            MailUtils.sendMail(MailUtils.EMAIL, "设置审批权限失败", e.getMessage());
        }
    }

    private static Set<String> getIds(String flows) {
        flows = flows.replaceAll("\\|\\|", ",").replaceAll("&&", ",");

        List<String> list = ListHelper.string2StringList(flows);

        return list.stream().filter(ValidateUtil::isInteger).collect(Collectors.toSet());
    }

    /**
     * 新增模板时,条件审批流添加审批处理权限
     *
     * @param list
     * @param user
     * @throws Throwable
     */
    public static void addAuthJudgerInConditionFlow(List<ConditionFlow> list, User user) {
        try {
            Set<String> set = new HashSet<>();
            for (ConditionFlow conditionFlow : list) {
                Set<String> ids = getIds(conditionFlow.getRequestFlow());
                if (Utils.isNotEmpty(ids)) {
                    set.addAll(ids);
                }
            }
            if (Utils.isEmpty(set)) {
                return;
            }
            RocketUtils.sendAddAuthMsg(Utils.collection2string(set), user.getCompanyId());
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            MailUtils.sendMail(MailUtils.EMAIL, "条件审批流设置权限失败", e.getMessage());
        }
    }


}
